package com.bitejiuyeke.forum.services.impl;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 666
 * Date: 2023-11-29
 * Time: 23:28
 */

import com.bitejiuyeke.forum.common.AppResult;
import com.bitejiuyeke.forum.common.ResultCode;
import com.bitejiuyeke.forum.dao.UserMapper;
import com.bitejiuyeke.forum.exception.ApplicationException;
import com.bitejiuyeke.forum.model.User;
import com.bitejiuyeke.forum.services.IUserService;
import com.bitejiuyeke.forum.utils.MD5Util;
import com.bitejiuyeke.forum.utils.StringUtil;
import com.bitejiuyeke.forum.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 *
 */
@Slf4j
@Service
public class UserServiceImpl implements IUserService {
    @Resource
    UserMapper userMapper;

    @Override
    public void createNormalUser(User user) {
        // 非空校验
        if (user == null || StringUtil.isEmpty(user.getUsername()) || StringUtil.isEmpty(user.getNickname()) || StringUtil.isEmpty(user.getSalt())) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //2.查询用户信息
        User existsUser = userMapper.selectByUserName(user.getUsername());
        //判断用户是否存在
        if (existsUser != null) {
            //打印日志
            log.info(ResultCode.AILED_USER_EXISTS.toString());
            //抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.AILED_USER_EXISTS));
        }
        //
// 除了注册时传⼊的有效值，其他全部使⽤默认
        if (user.getGender() == null) {
// 性别赋默认值
            user.setGender((byte) 2);
        }
// 填充默认值
        user.setIsAdmin((byte) 0);
        user.setAvatarUrl(null);
        user.setArticleCount(0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);
        int row = userMapper.insertSelective(user);
        if (row != 1) {
// 记录⽇志
            log.info(ResultCode.FAILED_CREATE.toString() + "username = " +
                    user.getUsername());
// 抛出异常
            throw new
                    ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
// 记录⽇志
        log.info("新增⽤⼾成功：username = " + user.getUsername());
    }

    @Override
    public User selectByUserName(String username) {
        // 非空校验
        if (StringUtil.isEmpty(username)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //返回查询结果
        return userMapper.selectByUserName(username);
    }

    @Override
    public User login(String username, String password) {
        //非空校验
        if (StringUtil.isEmpty(username) || StringUtil.isEmpty(password)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //查询用户信息
        User user = selectByUserName(username);
        //对查询结果做非空校验
        if (user == null) {
            log.warn(ResultCode.FAILED_LOGIN.toString() + ", username = " + username);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //对密码做校验
        String encryptPassword = MD5Util.md5(password, user.getSalt());
        // 与数据库存储的密文进行比较
        if (!encryptPassword.equalsIgnoreCase(user.getPassword())) {
            log.warn(ResultCode.FAILED_LOGIN.toString() + ", 密码错误， username = " + username);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        log.info("登录成功， username = " + username);
        //登录成功，返回用户信息
        return user;
    }

    @Override
    public User selectById(Long id) {
        if (id == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        // 调用DAO查询数据库并获取对象
        User user = userMapper.selectByPrimaryKey(id);
        //  返回结果
        return user;
    }

    @Override
    public void addOneArticleCountById(Long id) {
        if (id == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            log.warn(ResultCode.ERROR_IS_NULL.toString() + ", 用户不存在， id = " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        User UpdateUser = new User();
        UpdateUser.setId(user.getId());
        UpdateUser.setArticleCount(user.getArticleCount() + 1);
        //更新数据库
        int row = userMapper.updateByPrimaryKeySelective(UpdateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString() + " 操作失败");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));

        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            log.warn(ResultCode.ERROR_IS_NULL.toString() + ", 用户不存在， id = " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //更新用户发帖数
        User UpdateUser = new User();
        UpdateUser.setId(user.getId());
        UpdateUser.setArticleCount(user.getArticleCount() - 1);
        if (UpdateUser.getArticleCount() < 0) {
            UpdateUser.setArticleCount(0);
        }
        //更新数据库
        int row = userMapper.updateByPrimaryKeySelective(UpdateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString() + " 操作失败");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));

        }
    }

    @Override
    public void modifyInfo(User user) {
        //非空校验
        if (user == null || user.getId() == null || user.getId() <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        //校验用户是否存在
        User user1 = userMapper.selectByPrimaryKey(user.getId());
        if (user1 == null) {
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //定义一个标志位
        boolean checkAttr = false;   //false 表示校验没通过
        //定义一个专门更新的对象，防止用户传入的对象设置其他的属性
        User updateUser = new User();
        updateUser.setId(user.getId());
        //对每一个参数进行校验并赋值

        if (!StringUtil.isEmpty(user.getUsername()) && !user1.getUsername().equals(user.getUsername())) {
            //对用户名进行唯一性检验
            User checkUser = userMapper.selectByUserName(user.getUsername());
            if (checkUser != null) {
                //打印日志
                log.warn(ResultCode.FAILED_USER_EXISTS.toString());
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
            }
            updateUser.setUsername(user.getUsername());
            //更新标志位
            checkAttr = true;
        }
        //校验昵称
        if (!StringUtil.isEmpty(user.getNickname()) && !user1.getNickname().equals(user.getNickname())) {
            //设置昵称
            updateUser.setNickname(user.getNickname());
            //更新标志位
            checkAttr = true;
        }
        //校验性别
        if (user.getGender() != null && user.getGender() != user1.getGender()) {
            //设置性别
            updateUser.setGender(user.getGender());
            //更新标志位
            if(updateUser.getGender() >2 || updateUser.getGender() < 0){
                updateUser.setGender((byte) 2);
            }
            checkAttr = true;
        }
        //校验邮箱
        if (!StringUtil.isEmpty(user.getEmail()) && !user.getEmail().equals(user1.getEmail())) {
            //设置邮箱
            updateUser.setEmail(user.getEmail());
            //更新标志位
            checkAttr = true;
        }
        //校验手机号
        if (!StringUtil.isEmpty(user.getPhoneNum()) && !user.getPhoneNum().equals(user1.getPhoneNum())) {
            //设置手机号
            updateUser.setPhoneNum(user.getPhoneNum());
            //更新标志位
            checkAttr = true;
        }
        //校验个人简介
        if (!StringUtil.isEmpty(user.getRemark()) && !user.getRemark().equals(user1.getRemark())) {
            //设置个人简介
            updateUser.setRemark(user.getRemark());
            //更新标志位
            checkAttr = true;
        }
        //判断校验位
        if (checkAttr == false) {
            //打印日志
            //参数异常
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //执行sql
        int i = userMapper.updateByPrimaryKeySelective(updateUser);

        if (i != 1) {
            //打印日志
            //更新失败
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        //非空校验
        if(id == null || StringUtil.isEmpty(newPassword) || StringUtil.isEmpty(oldPassword)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if(user == null || user.getDeleteState()==1){
         //    打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));        }
        //校验旧密码
        //对老密码进行加密，获取密文
        String oldEncryptPassword = MD5Util.md5(oldPassword, user.getSalt());
        //判断密文是否一致
        if(!oldEncryptPassword.equalsIgnoreCase(user.getPassword())){
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        //生成新的盐
        String newSalt = UUIDUtil.UUID_32();
        //生成新密码的密文
        String encryptPassword = MD5Util.md5(newPassword, newSalt);

        //更新用户信息
        User  updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setPassword(encryptPassword);
        updateUser.setSalt(newSalt);
        updateUser.setUpdateTime(new Date());
        //调用dao
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1){

            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }

    }
}
